package org.rabbit.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.rabbit.pojo.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@WebFilter("/*")
@Component
public class LoginFilter implements Filter{

	@Resource
	private RedisTemplate<String,User> redisTemplate;

	@Override
	public void doFilter(ServletRequest request2, ServletResponse response2, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest)request2;
		HttpServletResponse response=(HttpServletResponse)response2;
		
		Cookie[] cookies = request.getCookies();
		String tokenId=null;
		
		for (Cookie cookie : cookies) {
			if(cookie.getName().equals("token")) {
				tokenId=cookie.getValue();
				break;
			}
		}
		ValueOperations<String, User> ops = redisTemplate.opsForValue();
		User user = ops.get(tokenId);
		System.out.println(user+"************");
		System.out.println(user==null);
		if(user==null) {
			/* 允许跨域的主机地址 */
			response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8020");
			/* 允许跨域的请求方法GET, POST, HEAD 等 */
			response.setHeader("Access-Control-Allow-Methods", "http://127.0.0.1:8020");
			/* 重新预检验跨域的缓存时间 (s) */
//			response.setHeader("Access-Control-Max-Age", "3600");
//			/* 允许跨域的请求头 */
//			response.setHeader("Access-Control-Allow-Headers", "http://127.0.0.1:8020");
			/* 是否携带cookie */
			response.setHeader("Access-Control-Allow-Credentials", "true");

//			设置返回json格式
			response.setContentType("application/json;charset=utf-8");// 指定返回的格式为JSON格式
//			 设置字符编码
			response.setCharacterEncoding("UTF-8");// setContentType与setCharacterEncoding的顺序不能调换，否则还是无法解决中文乱码的问题
//			 手动拼接json串
			String jsonStr = "{\"flag\":\"no\"}";
			PrintWriter out = null;
			out = response.getWriter();
			out.write(jsonStr);
			out.close();
			
		}else {
			chain.doFilter(request, response);
		}
		
		
	}
	
	
	
}
